import cn.hutool.core.io.FileUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ImageMerger {
    public static void main(String[] args) {
        List<BufferedImage> images = new ArrayList<>();
        // 假设图片文件名为image1.jpg, image2.jpg,..., image40.jpg
//        for (int i = 1; i <= 40; i++) {
//            try {
//                File file = new File("image" + i + ".jpg");
//                BufferedImage image = ImageIO.read(file);
//                images.add(image);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        FileUtil.loopFiles(new File("D:\\zmq\\work-software\\dynamic_datasource\\src\\main\\resources\\tess4j\\split"))
                .forEach(file -> {
                    BufferedImage image = null;
                    try {
                        image = ImageIO.read(file);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    images.add(image);
                });

        int rows;
        int cols;
        // 计算行数和列数，尽量接近正方形
        if (Math.sqrt(40) % 1 <= 0.5) {
            rows = (int) Math.floor(Math.sqrt(40));
        } else {
            rows = (int) Math.ceil(Math.sqrt(40));
        }
        cols = (int) Math.ceil((double) 40 / rows);

        // 获取单张图片的宽度和高度
        int width = images.get(0).getWidth();
        int height = images.get(0).getHeight();

        // 创建合并后的图片
        BufferedImage mergedImage = new BufferedImage(cols * width, rows * height, BufferedImage.TYPE_INT_RGB);

        int index = 0;
        for (int y = 0; y < rows; y++) {
            for (int x = 0; x < cols; x++) {
                if (index < 40) {
                    BufferedImage img = images.get(index);
                    for (int i = 0; i < width; i++) {
                        for (int j = 0; j < height; j++) {
                            mergedImage.setRGB(x * width + i, y * height + j, img.getRGB(i, j));
                        }
                    }
                    index++;
                }
            }
        }

        try {
            File output = new File("D:\\zmq\\work-software\\dynamic_datasource\\src\\main\\resources\\tess4j\\merge\\mergedImage.jpg");
            ImageIO.write(mergedImage, "jpg", output);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}